//
//  ShakeViewController.m
//  Conference
//
//  Created by chenxin on 12-11-15.
//
//

#import "ShakeViewController.h"
#import "DrawerView.h"
#import "WebData.h"
#import "Globals.h"
#import "Member.h"
#import "Constant.h"
#import "NetContant.h"
#import "ShakeViewCellController.h"
#import "SettingController.h"
#import <AudioToolbox/AudioToolbox.h>
@interface ShakeViewController ()

@end

@implementation ShakeViewController
@synthesize shakeView;
@synthesize arrayOfData;
@synthesize table;
@synthesize isShake;
@synthesize drawerView;
@synthesize player;
//@synthesize lastAcceleration;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //    NSString *path = [[NSBundle mainBundle] pathForResource:@"shake" ofType:@"wav"];
    //	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
    
    self.isShake=NO;
    self.arrayOfData=[NSMutableArray arrayWithCapacity:0];
    self.table=[[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320,330) style:UITableViewStylePlain]autorelease];
    self.table.delegate=self;
    self.table.dataSource=self;
    self.table.separatorStyle=NO;
    
    //    DrawerView *drawerView 
    self.drawerView= [[[DrawerView alloc]initWithView:self.table parentView:self.view] autorelease];
    
    [self.view addSubview:drawerView];
    
    //    [[UIApplication sharedApplication]setApplicationSupportsShakeToEdit:YES];
    //    [self becomeFirstResponder];
    
    
    NSString *soundPath= [[NSBundle mainBundle] pathForResource:@"shake" ofType:@"wav"];
    NSURL *soundUrl=[[NSURL alloc] initFileURLWithPath:soundPath]; 
    self.player=[[[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil]autorelease];
    [self.player prepareToPlay]; 
    [soundUrl release]; 
    
}
- (void)viewDidAppear:(BOOL)animated {
    
    [self becomeFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [self becomeFirstResponder];
}


- (BOOL)canBecomeFirstResponder {
    return YES;
}

-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    //检测到晃动
    [self.player play];
    AudioServicesPlaySystemSound ( kSystemSoundID_Vibrate) ;
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    //摇动取消
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    //摇动结束
    if(!self.isShake){
        [self doShake];
        self.isShake=YES;
    }
    
    //    if (event.subtype == UIEventSubtypeMotionShake) {
    //        //something happens
    //    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)doShake{
    NSThread *thread=[[[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil] autorelease];
    [thread start];
}

-(void)run{
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    NSString *sRet=[[WebData getInstance]getRandMember];
    
    [self performSelectorOnMainThread:@selector(onPostExecute:) withObject:sRet waitUntilDone:YES];
    
	[pool release];
    
}

-(void)onPostExecute:(NSString *)sRet{
    
    if ([sRet isEqualToString:[[NetContant getInstance] NET_CONNECT_FALSE]]) {
        
        
        //[[Globals getInstance] showAlertView:[[Constant getInstance] net_error]];
        
        
    }else if([sRet isEqualToString:[[NetContant getInstance] NETWORK_RECORD_ISEMPTY]]){
        
        //[[Globals getInstance] showAlertView:[[Constant getInstance] account_error]];
        
    }else {
        @try {
            [self doNetRet:sRet];
            [self doNetInfo];
        }
        @catch (NSException *exception) {
            
        }
        
        
        
    }
    
}
-(void)doNetRet:(NSString*)sRet{
    NSArray *tables=[sRet componentsSeparatedByString:[NetContant getInstance].TABLES_SPLIT_FLAG];
    [self.arrayOfData removeAllObjects];
    for(int i=0;i<[tables count];i++){
        if (nil!=[tables objectAtIndex:i]) {
            Member *userInfo=[[Member alloc]init];
            NSArray *info=[[tables objectAtIndex:i]componentsSeparatedByString:[NetContant getInstance].RECORDS_SPLIT_FLAG];
            if(nil==info||[info count]<7){
                
            }
            userInfo.memberId=[[info objectAtIndex:0]intValue];
            userInfo.firstName=[info objectAtIndex:1];
            userInfo.lastName=[info objectAtIndex:2];
            userInfo.gender=YES;
            if(![@"True" isEqualToString:[info objectAtIndex:3]])
                userInfo.gender=NO;
            userInfo.companyName=[info objectAtIndex:4];
            userInfo.mobile=[info objectAtIndex:5];
            userInfo.phone=[info objectAtIndex:6];
            [self.arrayOfData addObject:userInfo];
            
            [userInfo release];
        }
    }
    
}
-(void)doNetInfo{
    
    [self.drawerView showDrawerView];
    [self.table reloadData];
    self.isShake=NO;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.arrayOfData count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *shakeCell=@"shakeCell";
    ShakeViewCellController *cell=(ShakeViewCellController *)[tableView dequeueReusableCellWithIdentifier:shakeCell];
    if(cell ==nil){
		NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"ShakeViewCellController" owner:self options:nil];
		for (id oneObject in array) {
			if ([oneObject isKindOfClass:[ShakeViewCellController class]]) {
				cell=oneObject;
				break;
			}
		}
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    Member *data=[self.arrayOfData objectAtIndex:[indexPath row]];
    if(nil==data.firstName)
        data.firstName=@"";
    if(nil==data.lastName)
        data.lastName=@"";
    cell.lab_name.text=[NSString stringWithFormat:@"%@%@",data.firstName,data.lastName];
    cell.lab_company.text=data.companyName;
    cell.lab_info.text=data.mobile;
    return cell;
    
    
}


-(void)tableView:(UITableView *)tableView1 didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}


- (void)dealloc {
    [player stop];
    [player release];
    [drawerView release];
    [arrayOfData release];
    [shakeView release];
    [table release];
    [shakeView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setPlayer:nil];
    [self setDrawerView:nil];
    [self setArrayOfData:nil];
    [self setShakeView:nil];
    [self setTable:nil];
    [self setShakeView:nil];
    [super viewDidUnload];
}
- (IBAction)settingAction:(id)sender {
    SettingController *settingController=[[SettingController alloc]initWithNibName:@"SettingController" bundle:nil];
    [self.navigationController pushViewController:settingController animated:YES];
    [settingController release];
}
@end
